#include <iostream>
#include <chrono>
#include <judge/sandbox.h>

using json = nlohmann::json;
using namespace judge;
int main()
{
    json config = {
        {"submission_id", "test-001"},
        {"source_code", "I2luY2x1ZGU8aW9zdHJlYW0+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbWFpbigpewogICAgc3RkOjpjb3V0PDwiaGVsbG8gd29ybGQhIiA8PCBzdGQ6OmVuZGw7CiAgICByZXR1cm4gMDsKfQ=="},
        {"time_limit", 1000},    // 毫秒 (整数)
        {"memory_limit", 65536}, // KB (整数)
        {"test_cases", json::array({{{"id", 1},
                                     {"input", "MSAyCg=="},
                                     {"expected_output", "Mwo="},
                                     {"time_limit", 500}, // 可覆盖全局限制
                                     {"memory_limit", 32768}},
                                    {{"id", 2},
                                     {"input", "MTAwIDIwMAo="},
                                     {"expected_output", "MzAwCg=="}}})}};

    try
    {
        // 类型安全检查
        if (!config["submission_id"].is_string())
        {
            throw std::runtime_error("submission_id must be string");
        }
        if (!config["source_code"].is_string())
        {
            throw std::runtime_error("source_code must be string");
        }
        Sandbox sandbox;
        JudgeResult result = sandbox.judge(config);

        std::cout << "=== 评测结果 ===" << std::endl;
        std::cout << "最终判定: " << verdictToString(result.verdict) << std::endl;
        std::cout << "总用时: " << result.total_time.count() << "ms" << std::endl;
        std::cout << "峰值内存: " << result.max_memory << "KB" << std::endl;
        std::cout << "\n=== 测试用例详情 ===" << std::endl;
        for (const auto &test : result.results)
        {
            std::cout << "\n[用例 " << test.case_id << "]" << std::endl;
            std::cout << "判定: " << verdictToString(test.verdict) << std::endl;
            std::cout << "用时: " << test.time_used.count() << "ms" << std::endl;
            std::cout << "内存: " << test.memory_used << "KB" << std::endl;
            std::cout << "实际输出:\n"
                      << test.output << std::endl;
        }
    }
    catch (const json::exception &e)
    {
        std::cerr << "JSON错误: " << e.what() << "\nID: " << e.id << std::endl;
        return 1;
    }
    catch (const std::exception &e)
    {
        std::cerr << "系统错误: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}